import { setConfig } from "./config";
//导入入口文件
import performance from "./performance/index";
import error from "./error/index";
import behavior from "./behavior/index";
import { lazyReportBatch } from "./report";

window.__webEyeSDK__ = {
  version: "0.0.1",
};

// 针对Vue项目的错误捕获
function install(Vue, options) {
  if (__webEyeSDK__.vue) {
    return;
  }
  __webEyeSDK__.vue = true;
  const handler = Vue.config.errorHandler;
  Vue.config.errorHandler = function (err, vm, info) {
    const reportData = {
      info,
      error: err.stack,
      subType: "vue",
      type: "error",
      startTime: window.performance.now(),
      pageURL: window.location.href,
    };
    lazyReportBatch(reportData);
    if (handler) {
      handler.call(this, err, vm, info);
    }
  };
}

// 定义一个错误边界函数
function errorBoundary(err, info) {
  // 如果__webEyeSDK__中有react属性，则返回
  if (__webEyeSDK__.react) return;
  // 否则，将__webEyeSDK__中的react属性设置为true
  __webEyeSDK__.react = true;
  // todo: 上报具体的错误信息
  // todo: 上报具体的错误信息
  // 定义一个reportData对象，包含错误信息、info、subType、type、startTime、pageURL
  const reportData = {
    error: err?.stack,
    info,
    subType: "react",
    type: "error",
    startTime: window.performance.now(),
    pageURL: window.location.href,
  };
  // 调用lazyReportBatch函数，将reportData作为参数传入
  lazyReportBatch(reportData);
}

// 导出一个名为init的函数，接收一个参数options
function init(options) {
  // 调用setConfig函数，传入参数options
  setConfig(options);
  performance();
  error();
  behavior();
}

export default {
  install,
  errorBoundary,
  performance,
  error,
  behavior,
  init,
};
